<?php

date_default_timezone_set('Europe/Kiev');
define('DEBUG', file_exists('debug'));

if (DEBUG) {
    ini_set('error_reporting', E_ALL);
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
} else {
    ini_set('error_reporting', 0);
    ini_set('display_errors', 0);
    ini_set('display_startup_errors', 0);
}

set_exception_handler(function (Exception $e) {
    if (DEBUG) {
        echo '<h1>Exception</h1>';
        echo '<b>' . $e->getFile() . ':' . $e->getLine() . '</b><br/>';
        echo $e->getMessage() . '<br/><pre>' . print_r($e->getTrace(), true) . '</pre>';
        exit;
    } else {
        die('<h1 style="text-align: center"><b>Internal Error</b></h1>');
    }
});

if (DEBUG) {
    $__phpErrors = [];

    set_error_handler(function ($number, $message, $file, $line) use (&$__phpErrors) {

        switch ($number) {
            case E_USER_ERROR:
                $errorType = 'Error';
                break;
            case E_WARNING:
            case E_USER_WARNING:
                if (false !== strpos($file, '/Zend/') || false !== strpos($file, '/Smarty/')) {
                    return;
                }
                $errorType = 'Warning';
                break;
            case E_NOTICE:
            case E_USER_NOTICE:
                if (false !== strpos($file, '/data/view_c/')) {
                    return;
                }
                $errorType = 'Notice';
                break;
            default:
                $errorType = 'Unknown error';
                break;
        }

        $__phpErrors[] = compact('errorType', 'message', 'file', 'line');
    }, E_ALL);

    register_shutdown_function(function () use (&$__phpErrors) {
        $headers = apache_response_headers();
        if (array_key_exists('Location', $headers) || !empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
            return;
        }
        /** @var Zend_Db_Profiler_Query $profile */
        if ($profiles = \Application\Db::getInstance()->getProfiler()->getQueryProfiles()) {
            foreach ($profiles as $profile) {
                echo $profile->getQuery() . '<br/>';
            }
        }
        if (count($__phpErrors)) {
            printf('<b>PHP Errors (%d):</b><br>', count($__phpErrors));
        } else {
            return;
        }
        $i = 0;
        foreach ($__phpErrors as $error) {
            $i++;
            printf("%d) <b>%s:</b> %s in <b>%s</b> on line <b>%d</b><br>",
                    $i, $error['errorType'], $error['message'], $error['file'], $error['line']);
        }
    });

}
set_include_path(__DIR__ . '/../module' . PATH_SEPARATOR . __DIR__ . '/../lib');
require_once('Zend/Loader/Autoloader.php');
require_once('Zend2/Zend/Loader/AutoloaderFactory.php');

$autoLoader = Zend_Loader_Autoloader::getInstance();
$autoLoader->setFallbackAutoloader(true);

Zend\Loader\AutoloaderFactory::factory(array(
    'Zend\Loader\StandardAutoloader' => array(
        'autoregister_zf' => true
    )
));

if (!isset($_SERVER['REQUEST_URI'])) {
    throw new Exception('No REQUEST_URI');
}

$router = Zend\Mvc\Router\Http\TreeRouteStack::factory();
$config = Application\Config::getInstance();

foreach ($config['modules'] as $module) {
    $moduleConfig = include($config['paths']['module'] . '/' . $module . '/config/module.config.php');
    if ($moduleConfig && array_key_exists('router', $moduleConfig)) {
        $router->addRoutes($moduleConfig['router']['routes']);
    }
}
/** @var Zend\Http\PhpEnvironment\Request $request */
$request = Application\Request::getInstance();
if ($routeMatch = $router->match($request)) {
    $class  = $routeMatch->getParam('controller');
    if (class_exists($class)) {
        /** @var \Application\ControllerAbstract $controller */
        $controller = new $class();
        $controller->setRouteMatch($routeMatch);
        $controller->callAction($routeMatch->getParam('action'));
    } else {
        throw new Exception('Controller class ' . $class . ' not exist');
    }
} else {
    $controller = new Application\Controller();
    $controller->notFoundAction($request->getRequestUri());
}
